import Papa from "papaparse";
import * as FS from "file-saver";
import { ref } from "vue";
export function convert(dataJson, options, header) {
  let { transform } = options;
  let dataCSV = null;
  if (typeof header === "undefined" || header === "") {
    dataCSV = Papa.unparse(dataJson, options);
  } else {
    var d = {
      fields: Object.values(header),
      data: [],
    };
    for (let i = 0; i < dataJson.length; i++) {
      var a = [];
      for (let key in header) {
        if (transform && typeof transform[key] === "function") {
          const ret = transform[key](dataJson[i], i);
          a.push(ret);
        } else {
          let o = dataJson?.[i] ?? {};
          let result = o?.[key] ?? "";
          a.push(result + "");
        }
      }
      d.data.push(a);
    }
    dataCSV = Papa.unparse(d, options);
  }
  return dataCSV;
}

export async function download(filename, dataJson, options, header) {
  let dataCSV = convert(dataJson, options, header);
  filename = `${filename}.csv`;
  if (typeof dataCSV === "undefined" || dataCSV === "") {
    throw new Error("no data");
  }
  const blob = new Blob(["\ufeff", dataCSV], {
    type: "text/csv;charset=utf-8",
  });
  FS.saveAs(blob, filename);
}

export function listConvertTree(arr = []) {
  const tableData = ref(arr);
  tableData.value = tableData.value.map((item) => ({
    ...item,
    children: [],
    hasChildren: false,
  }));
  // 将子级数据添加到对应父级的children属性中
  for (const item of tableData.value) {
    if (item.dataType.indexOf("Array") !== -1) {
      item.hasChildren = true;
    }
  }
  return tableData.value;
}

export function exportByBlob(data, fileName) {
  let blob = null;
  const fileType = data.type;
  fileName = fileName.replace(/[\/\\:*?"<>|]/g, "-");
  switch (fileType) {
    case "application/csv":
      fileName = fileName + ".csv";
      blob = new Blob([data]);
      break;
    default:
      blob = new Blob([data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      }); // 此处为生成doc
      break;
  }

  let link = document.createElement("a");
  let href = window.URL.createObjectURL(blob);
  link.href = href;
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(href); // 释放掉blob对象
}
